package com.atguigu2.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty
 *
 * @author sunfeng
 * @date 2021/03/29 09:28
 * handler 对应bossGroup   childHandler 对应workerGroup
 *
 *
 **/
@Slf4j
public class NioSocketServer {
    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //创建服务端启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置相应参数  设置boosGroup 和workerGroup
            bootstrap.group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到的链接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动链接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NioSocketServerHandler());
                        }
                    });
            System.out.println("准备完毕");

            ChannelFuture channelFuture = bootstrap.bind(8888).sync();

            channelFuture.channel().closeFuture().sync();

        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }

    }

}
